

import { DatePicker, DatePickerProps } from 'antd';
import dayjs from 'dayjs';
import './forms.scss';
import { useFormItemInit } from './hooks';
import { FormItemBaseProps } from './interface';
import 'dayjs/locale/zh-cn';
import updateLocale from 'dayjs/plugin/updateLocale';
import React from 'react';
import { useDrag } from './drop.hooks';
import Readonly from './Readonly';
import { Utils } from '../../utils/utils';
import { Components } from '../..';
dayjs.extend(updateLocale);




/** 日期格式 */
type DateFormatType = 'YYYY-MM-DD' | 'YYYY-MM-DD HH:mm:ss' | 'YYYY-MM-DD HH:mm' | 'YYYY-MM-DD HH';

/** 日期 转换为 Dayjs日期 */
const dateToDayjs = (value: any, dateFormat = 'YYYY-MM-DD'): dayjs.Dayjs | null => {
    if (Utils.isEmpty(value)) {
        return null;
    } else {
        return dayjs(value, dateFormat);
    }
}
/** Dayjs日期 转换为 字符串日期 */
const dayjsToDate = (value: dayjs.Dayjs, dateFormat = 'YYYY-MM-DD'): string => {
    return dayjs(value).format(dateFormat);
}

interface IProps extends FormItemBaseProps {
}
export default function MyDate(props: IProps) {
    const { formControl, className = '', style={} } = props;
    const {
        value, setValue,
        readonly,
        outerClassName,
        layout,
        showError,
        outerStyle,
        labelStyle,
        selectorStyle,
    } = useFormItemInit(formControl, className, style);

    const dateFormat: DateFormatType = 'YYYY-MM-DD';

    const onDatePickerChange = (_date: dayjs.Dayjs, dateString: string | string[]) => {
        setValue(dateString);
        formControl.setValue(dateString);
    };

    const onDatePickerOk = (date: dayjs.Dayjs) => {
        const dateString = dayjsToDate(date, dateFormat);
        setValue(dateString);
        formControl.setValue(dateString);
    };

    const datePickerProps: DatePickerProps = {
        placeholder: formControl.controlData.placeholder || '请选择日期',
        value: dateToDayjs(value, dateFormat),
        className: 'date-picker',
        picker: 'date',
        // showTime: { minuteStep: 15, },
        format: dateFormat,
        allowClear: true,
        onChange: onDatePickerChange,
        onOk: onDatePickerOk,
        disabled: readonly,
        status: showError ? 'error' : undefined,
        style: selectorStyle,
    };

    /** 拖拽排序 */
    const dropRef = React.useRef<HTMLDivElement>(null);
    useDrag({ dropRef, formControl });

    return (
        <div component-name='form-item' className={outerClassName} style={outerStyle} ref={dropRef}>
            <div className={`field ${layout}`}>
                <Components.forms.FormLabel formControl={formControl} style={labelStyle} />
                <div className='control'>
                    <div className="value">
                        {
                            readonly ? <Readonly formControl={formControl} /> : <DatePicker  {...datePickerProps} />
                        }
                    </div>
                </div>
            </div>

        </div>
    )
}
